﻿using PlutoStudio.Net.Processors.Attributes;
using PlutoStudio.Net.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace PlutoStudio.Net.Processors
{
    public abstract class MessageProcessorBase : IMessageProcessor
    {
        internal protected NetContext Context { get; private set; }
        public Message Message { get; private set; }
        public StatusCode StatusCode { get; set; }
        public EndPoint RemoteEndPoint { get; private set; }
        public MessageProcessorBase()
        {
            StatusCode = StatusCode.OK;
        }

        void IMessageProcessor.Process(NetContext context, ReceivedEventArgs e)
        {
            
            TraceHelper.Helper.TraceInformation(string.Format("正在处理消息:{0}", e.Message));
            this.Context = context;
            this.Message = e.Message as Message;
            this.StatusCode = GetStatusCode();
            this.RemoteEndPoint = e.RemoteEndPoint;
            if (this.StatusCode!= Processors.StatusCode.OK)
            {
                if (OnFaildMessage())
                {
                    return;
                }
            }
            var action = this.GetAtion();
            action.ExecuteAction(this);
        }

        protected virtual bool OnFaildMessage()
        {
            return false;
        }
        protected virtual StatusCode GetStatusCode()
        {
            return StatusCode.OK;
        }
        
        public ActionResult Json(object data)
        {
            return new JsonResult(data);
        }

        public ActionResult Content(string content)
        {
            return new ContentResult(content);
        }

        public ActionResult Void()
        {
            return new EmptyResult();
        }

        public void SetStatusCode(StatusCode code)
        {
            this.StatusCode = code;
        }
    }
}
